package com.zhoug.chart3demo.chart;

import android.graphics.Color;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;

import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.model.GradientColor;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.zhoug.chart3.MPChartColors;
import com.zhoug.chart3.charts.MPBarChart;
import com.zhoug.chart3.core.styleconfig.IMPBarStyleConfig;
import com.zhoug.chart3.data.HkChartData;
import com.zhoug.chart3.data.OnDateSetCreateListener;
import com.zhoug.chart3.formatters.MPDataSetValueFormatter;
import com.zhoug.chart3.markers.MPCombinedMarker;
import com.zhoug.chart3.utils.MPChartUtils;
import com.zhoug.chart3demo.BaseActivity;
import com.zhoug.chart3demo.R;
import com.zhoug.common3.http.SchedulerUtils;
import com.zhoug.common3.utils.TextUtils;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;


/**
 * 柱状图
 *
 * @Author: zhoug
 * @Date: 2024-01-30
 * @Description:
 */
public class BarChartActivity extends BaseActivity {
    private int mXNum;
    private int mYNum;
    private boolean mStack;
    private boolean mOverLap;
    private int mOneScreenNum;
    private boolean mAutoScale;
    private MPBarChart mBarChart1;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Switch mSwitchStack;
    private EditText mEtXSize;
    private EditText mEtYSize;
    private Button mBtnSetting;
    private Switch mSwitchAutoScale;
    private EditText mEtOneScreenMinNum;
    private MPBarChart mBarChart2;
    private EditText mEtBarWidth;
    private EditText mEtGroupSpace;
    private EditText mEtBarSpace;
    private Switch mSwitchPercent;
    private Switch mSwitchArc;
    private Switch mSwitchGradientColors;
    private Switch mSwitchOverLap;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_barchart;
    }

    @Override
    protected void findViews() {
        mBarChart1 = findViewById(R.id.barChart1);
        mSwipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        mSwitchStack = findViewById(R.id.switchStack);
        mEtXSize = findViewById(R.id.et_xSize);
        mEtYSize = findViewById(R.id.et_ySize);
        mBtnSetting = findViewById(R.id.btn_setting);
        mSwitchAutoScale = findViewById(R.id.switchAutoScale);
        mEtOneScreenMinNum = findViewById(R.id.et_oneScreenMinNum);
        mBarChart2 = findViewById(R.id.barChart2);
        mEtBarWidth = findViewById(R.id.et_barWidth);
        mEtGroupSpace = findViewById(R.id.et_groupSpace);
        mEtBarSpace = findViewById(R.id.et_barSpace);
        mSwitchPercent = findViewById(R.id.switchPercent);
        mSwitchArc = findViewById(R.id.switchArc);
        mSwitchGradientColors = findViewById(R.id.switchGradientColors);
        mSwitchOverLap = findViewById(R.id.switchOverLap);
    }

    private static final int[] colors = {MPChartColors.COLOR_RED, MPChartColors.COLOR_BLUE, MPChartColors.COLOR_GREEN,
            MPChartColors.COLOR_SOIL, MPChartColors.COLOR_DEEP_PURPLE, MPChartColors.COLOR_LAVENDER, MPChartColors.COLOR_GRASS_GREEN,};
    private static final List<GradientColor> gradientColors = Arrays.asList(
            new GradientColor(MPChartColors.COLOR_RED, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_RED)),
            new GradientColor(MPChartColors.COLOR_BLUE, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_BLUE)),
            new GradientColor(MPChartColors.COLOR_GREEN, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_GREEN)),
            new GradientColor(MPChartColors.COLOR_SOIL, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_SOIL)),
            new GradientColor(MPChartColors.COLOR_DEEP_PURPLE, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_DEEP_PURPLE)),
            new GradientColor(MPChartColors.COLOR_LAVENDER, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_LAVENDER)),
            new GradientColor(MPChartColors.COLOR_GRASS_GREEN, MPChartUtils.setColorAlphaPercent(0.2f, MPChartColors.COLOR_GRASS_GREEN))
    );

    @Override
    protected void init() {
        boolean showAllGroupBar = true;
        boolean showTotalData = true;
        boolean showPercent = true;


        MPCombinedMarker combinedMarker = new MPCombinedMarker(this);
        combinedMarker.showSum(true);
        mBarChart1.setMarker(combinedMarker);
        mBarChart2.setMarker(new MPCombinedMarker(this));

        mBarChart1.setOnDateSetCreateListener(new OnDateSetCreateListener<BarDataSet>() {
            @Override
            public void onInitDataSetStyle(BarDataSet dataSet, int index) {
                dataSet.setDrawValues(false);
                dataSet.setValueFormatter(new MPDataSetValueFormatter());
            }
        });
        mBarChart2.setOnDateSetCreateListener(new OnDateSetCreateListener<BarDataSet>() {
            @Override
            public void onInitDataSetStyle(BarDataSet dataSet, int index) {
                dataSet.setDrawValues(true);
                dataSet.setValueFormatter(new MPDataSetValueFormatter());

            }
        });

        mBarChart1.getAxisRight().setEnabled(true);
        mBarChart2.getAxisRight().setEnabled(true);


        XAxis xAxis = mBarChart1.getXAxis();
        xAxis.setDrawGridLines(true);
        xAxis.setGridLineWidth(Color.parseColor("#0000ff"));
        xAxis = mBarChart2.getXAxis();
        xAxis.setDrawGridLines(true);
        xAxis.setGridLineWidth(Color.parseColor("#0000ff"));
        mSwipeRefreshLayout.setOnRefreshListener(this::loadData);
        mBtnSetting.setOnClickListener(v -> {
            setting();
            loadData();
        });
        mSwitchStack.setOnCheckedChangeListener(onCheckedChangeListener);
        mSwitchOverLap.setOnCheckedChangeListener(onCheckedChangeListener);
        mSwitchAutoScale.setOnCheckedChangeListener(onCheckedChangeListener);
        mSwitchPercent.setOnCheckedChangeListener(onCheckedChangeListener);
        mSwitchArc.setOnCheckedChangeListener(onCheckedChangeListener);
        mSwitchGradientColors.setOnCheckedChangeListener(onCheckedChangeListener);
        setting();
        loadData();
    }


    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = (buttonView, isChecked) -> {
        setting();
        loadData();
    };

    private void setting() {
        mStack = mSwitchStack.isChecked();
        mOverLap = mSwitchOverLap.isChecked();
        mAutoScale = mSwitchAutoScale.isChecked();
        boolean spaceIsPercent = mSwitchPercent.isChecked();
        boolean arc = mSwitchArc.isChecked();
        mXNum = TextUtils.parseInt(mEtXSize.getText().toString(), 12);
        mYNum = TextUtils.parseInt(mEtYSize.getText().toString(), 1);
        mOneScreenNum = TextUtils.parseInt(mEtOneScreenMinNum.getText().toString(), 0);
        float barWidth = TextUtils.parseFloat(mEtBarWidth.getText().toString(), 0);
        float barSpace = TextUtils.parseFloat(mEtBarSpace.getText().toString(), 0);
        float groupSpace = TextUtils.parseFloat(mEtGroupSpace.getText().toString(), 0);




        mBarChart1.setBarTopArcEnable(arc);
        mBarChart2.setBarTopArcEnable(arc);
        IMPBarStyleConfig barStyle = mBarChart1.getStyleConfig();
        barStyle.setAutoScaleMax(mAutoScale);
        barStyle.setBarWidth(barWidth);
        barStyle.setGroupSpace(groupSpace);
        barStyle.setBarSpace(barSpace);
        barStyle.setSpaceIsPercent(spaceIsPercent);
        barStyle.setOneScreen(mOneScreenNum);
        barStyle.setStackBar(mStack);
        barStyle.setOverlap(mOverLap);
        barStyle = mBarChart2.getStyleConfig();
        barStyle.setAutoScaleMax(mAutoScale);
        barStyle.setBarWidth(barWidth);
        barStyle.setGroupSpace(groupSpace);
        barStyle.setBarSpace(barSpace);
        barStyle.setSpaceIsPercent(spaceIsPercent);
        barStyle.setOneScreen(mOneScreenNum);
        barStyle.setStackBar(mStack);
        barStyle.setOverlap(mOverLap);
        boolean checked = mSwitchGradientColors.isChecked();
        if(checked){
            barStyle.setGradientColors(MPChartUtils.copyList(gradientColors,2));
        }else{
            barStyle.setGradientColors(null);

        }

    }


    private void loadData() {
        Disposable subscribe = Observable
                .create((ObservableOnSubscribe<List<HkChartData>>) emitter -> {
                    Thread.sleep(200);
                    Random random = new SecureRandom();
                   /* int r = random.nextInt(6);
                    if (r == 4) {
                        throw new Exception("接口发生异常");
                    }*/
                    List<HkChartData> list = new ArrayList<>();
                    for (int i = 1; i <= mXNum; i++) {
                        HkChartData chartData = new HkChartData();
                        chartData.setName(i + "月");
                        for (int j = 1; j <= mYNum; j++) {
                            float f = random.nextInt(10000) / 10000f;
//                            chartData.put("数量" + j, i * 100 + j * 40 +f );
                            if (i == 1) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 2 + f);
                                } else {
                                    chartData.put("数量" + j, 100 + j * 40 + f);
                                }
                            } else if (i == 2) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 5 + f);
                                } else {
                                    chartData.put("数量" + j, 100 + j * 40 + f);
                                }
                            } else if (i == 3) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 10 + f);
                                } else {
                                    chartData.put("数量" + j, 100 + j * 40 + f);
                                }
                            } else if (i == 4) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 20 + f);
                                } else {
                                    chartData.put("数量" + j, 100 + j * 40 + f);
                                }
                            } else if (i == 5) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 2 + f);
                                } else {
                                    chartData.put("数量" + j, 0);
                                }
                            } else if (i == 6) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 10 + f);
                                } else {
                                    chartData.put("数量" + j, 0);
                                }
                            } else if (i == 7) {
                                if (j == mYNum) {
                                    chartData.put("数量" + j, 20 + f);
                                } else {
                                    chartData.put("数量" + j, 0);
                                }
                            } else {
                                chartData.put("数量" + j, random.nextInt(100) + f);
                            }
                        }
                        list.add(chartData);
                    }

                    emitter.onNext(list);
                    emitter.onComplete();

                })
                .compose(SchedulerUtils.apply())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(data -> {
                    mSwipeRefreshLayout.setRefreshing(false);
                    mBarChart1.setHkChartData(data);
                    mBarChart2.setHkChartData(data);
                }, throwable -> {
                    mSwipeRefreshLayout.setRefreshing(false);
                    throwable.printStackTrace();
                    mBarChart1.error();
                    mBarChart2.error();
                });


    }

}
